var express = require('express')
var router = express.Router()

let roleList = [
    {roleId: '1', roleUrl: '', roleName: '椰羊不是羊', rolePassWord: '123456', role: '1'},
    {roleId: '2', roleUrl: '', roleName: '呵呵', rolePassWord: '741852', role: '2'},
    {roleId: '3', roleUrl: '', roleName: '哈哈', rolePassWord: '987654', role: '3'},
    {roleId: '4', roleUrl: '', roleName: '嘿嘿', rolePassWord: '369258', role: '4'},
]

router.get('/list', function(req, res, next) {

    let data = roleList.filter(item => {
        return item.roleName.includes(req.query.roleName)
    })

    res.send({
        data: data
    })
})

router.post('/add', function(req, res, next) {

    let data = {
        roleId: roleList.length + 1,
        roleUrl: req.body.roleUrl,
        roleName: req.body.roleName,
        rolePassWord: req.body.rolePassWord,
        role: req.body.role,
    }

    roleList.push(data)

    res.send({
        msg: '新增成功',
        code: 200,
        data: true
    })
})

router.put('/update', function (req, res, next) {
    if (!req.body.roleId) {
        res.send('缺少id字段')

        return
    }

    let index = roleList.findIndex(item => {
        return Number(item.roleId) === Number(req.body.roleId)
    })

    if (index < 0) {
        res.send({
            msg: '编辑失败，未通过roleId找到对应数据',
            code: 500,
            data: false
        })

        return
    }

    roleList[index] = Object.assign({}, req.body)

    res.send({
        msg: '编辑成功',
        code: 200,
        data: true
    })
})

router.delete('/delete', function (req, res, next) {
    if (!req.query.roleId) {
        res.send('缺少roleId字段')
    }

    let index = roleList.findIndex(item => {
        return Number(item.roleId) === Number(req.query.roleId)
    })

    if (index < 0) {
        res.send({
            msg: '删除失败，未能通过roleId找到对应数据',
            code: 500,
            data: false
        })
        return
    }

    roleList.splice(index, 1)

    res.send({
        msg: '删除成功',
        code: 200,
        data: true
    })
})

module.exports = router